<template>
  <div class="update-name">
    <!-- 导航栏 -->
    <van-nav-bar
      title="设置昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    ></van-nav-bar>

    <!-- 输入框 -->
    <div class="field-wrap">
      <van-field
        v-model.trim="localName"
        rows="2"
        autosize
        type="textarea"
        maxlength="6"
        placeholder="请输入昵称"
        show-word-limit
      />
    </div>
  </div>
</template>

<script>
import { updataUsername } from "@/api/user";
import store from "@/store";
import { mapMutations } from "vuex";
import { reRefrash_token, checkUsername } from "@/utils/setToken";

export default {
  name: "UpdataName",
  components: {},
  props: {
    value: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      // 输入框的值
      localName: this.value,
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    ...mapMutations("user", ["setToken"]),
    async onConfirm() {
      this.$toast.loading({
        message: "保存中...",
        forbidClick: true,
        duration: 0,
      });
      try {
        const localName = this.localName;
        if (!localName.length) {
          this.$toast("昵称不能为空");
          return;
        }
        // console.log(await checkUsername(localName));
        const result = await checkUsername(localName);
        if (!result) {
          this.$toast("昵称已存在");
        } else {
          console.log(store.getters.id);
          await updataUsername(
            store.getters.id,
            reRefrash_token({ username: this.localName })
          );
          this.$emit("input", localName);
          // console.log(data)
          this.$emit("close");
          this.$toast.success("修改成功");
          this.setToken(reRefrash_token({ username: this.localName }));
        }
      } catch (err) {
        this.$toast.fail("修改失败");
        console.log(err);
      }
    },
  },
};
</script>
<style lang='less' scoped>
.field-wrap {
  padding: 20px 0;
}
</style>
